const express = require('express');
const router = express.Router();
const db = require('../db');

// 获取所有人员
router.get('/', (req, res) => {
  db.all('SELECT * FROM employees ORDER BY serial_number', (err, rows) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json(rows);
  });
});

// 获取单个人员
router.get('/:id', (req, res) => {
  const id = req.params.id;
  db.get('SELECT * FROM employees WHERE id = ?', [id], (err, row) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    if (!row) {
      res.status(404).json({ message: '人员不存在' });
      return;
    }
    res.json(row);
  });
});

// 创建人员
router.post('/', (req, res) => {
  const { name, type, serial_number, feishu_user_id } = req.body;
  const sql = `INSERT INTO employees (name, type, serial_number, feishu_user_id)
               VALUES (?, ?, ?, ?)`;
  db.run(sql, [name, type, serial_number, feishu_user_id], function(err) {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.status(201).json({
      id: this.lastID,
      message: '人员创建成功',
      data: { id: this.lastID, name, type, serial_number, feishu_user_id }
    });
  });
});

// 更新人员
router.put('/:id', (req, res) => {
  const id = req.params.id;
  const { name, type, serial_number, feishu_user_id } = req.body;
  const sql = `UPDATE employees SET name = ?, type = ?, serial_number = ?,
               feishu_user_id = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`;
  db.run(sql, [name, type, serial_number, feishu_user_id, id], function(err) {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    if (this.changes === 0) {
      res.status(404).json({ message: '人员不存在' });
      return;
    }
    res.json({ message: '人员更新成功' });
  });
});

// 删除人员
router.delete('/:id', (req, res) => {
  const id = req.params.id;
  db.run('DELETE FROM employees WHERE id = ?', [id], function(err) {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    if (this.changes === 0) {
      res.status(404).json({ message: '人员不存在' });
      return;
    }
    res.json({ message: '人员删除成功' });
  });
});

// 根据类型获取人员
router.get('/getByType/:type', (req, res) => {
  const type = req.params.type;
  db.all('SELECT id, name, type, serial_number, feishu_user_id FROM employees WHERE type = ? ORDER BY serial_number', [type], (err, rows) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json({ data: rows });
  });
});

module.exports = router;